using System;
using System.IO;
using System.Net;
using UnityEngine;

namespace Sora.Tools.QueryHoliday
{
    public static class QueryHoliday
    {
        public static bool IsHoliday(string date)
        {
            bool? isHoliday = null;
            var result = GetResult($"https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={date}&resource_id=6018");
            var calendar = JsonUtility.FromJson<Core.Calendar>(result);
            foreach (var data in calendar.data)
            {
                foreach (var holiday in data.holiday)
                {
                    foreach (var list in holiday.list)
                    {
                        if (list.date == date)
                        {
                            isHoliday = list.status == 1;
                            break;
                        }
                    }

                    if (isHoliday != null) break;
                }

                if (isHoliday != null) break;
            }
            if (isHoliday == null) isHoliday = false;
            return isHoliday.Value;
        }

        static string GetResult(string url)
        {
            var request = WebRequest.Create(url);
            var response = request.GetResponse();
            var stream = response.GetResponseStream();
            var result = string.Empty;
            try
            {
                using (var reader = new StreamReader(stream))
                {
                    result = reader.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                Debug.LogError(e);
                throw;
            }
            finally
            {
                stream.Close();
            }

            return result;
        }
    }
}